package com.bjut.impl;

import com.bjut.constant.AuthConstants;
import com.bjut.factory.LoginStrategyFactory;
import com.bjut.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 项目自己的认证流程
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /**
         * String username:这个参数是springSecurity框架的唯一标识；
         * 这个参数是谁传呢？？？
         * 这个username就是前端传来的登录用户的用户名；
         */

        // 获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 从请求头中获取登录类型
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);

        // 判断请求来自于那个系统
//        if (AuthConstants.SYS_USER_LOGIN.equals(loginType)) {
//            // 商城后台管理体统流程
//        } else {
//            // 商城用户购物系统流程
//        }

        // 这里先判断一下类型字段是否为空
        if (!StringUtils.hasText(loginType)) {
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }
        // 根据登录策略工厂获取具体的登录策略对象
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        // 执行登录策略的真正登录方法，最终返回用户信息；
        return instance.realLogin(username);
    }
}
